package io.kimmking.gateway.config;

import io.kimmking.gateway.ratelimiter.MyRedisRateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.List;

@Configuration
@EnableConfigurationProperties(RateLimteConfig.class)
public class RateLimitAutoConfig {

    @Bean(name = "myRedisScript")
    @SuppressWarnings("unchecked")
    public RedisScript redisRequestRateLimiterScript() {
        DefaultRedisScript redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/rate_limit_redis.lua")));
        redisScript.setResultType(List.class);
        return redisScript;
    }

    @Autowired
    private RateLimteConfig rateLimteConfig;

    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    @Autowired
    @Qualifier("myRedisScript")
    private RedisScript script;

    @Bean
    @ConditionalOnMissingBean
    public MyRedisRateLimiter myRedisRateLimiter(){
        return new MyRedisRateLimiter(this.rateLimteConfig, this.redisTemplate, this.script);
    }

}
